import random

from django.core.validators import RegexValidator
from django.http import HttpResponse
from django.shortcuts import render

from utils.tencent.sms import send_sms_single
from django.conf import settings
from django.shortcuts import HttpResponse
from django_redis import get_redis_connection

# Create your views here.
def send_sms(request):
    """发送短信
        ?type=loggin ->1200801
        ?type=register ->1200794
    """
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse("模板不存在")

    code = random.randrange(100000, 999999)
    res = send_sms_single('18270029500', template_id, [code, ])
    if res['result'] == 0:
        print(res)
        return HttpResponse("成功")
    else:
        print(res)
        return HttpResponse("失败")


from django import forms
from blogAPP import models


class RegisterModelForm(forms.ModelForm):
    mobile_phone = forms.CharField(label='手机号', validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])
    password = forms.CharField(label='密码',
                               widget=forms.PasswordInput())
    confirm_password = forms.CharField(label='重复密码',
                                     widget=forms.PasswordInput())
    code = forms.CharField(label='验证码',
                           widget=forms.TextInput())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)
    class Meta:
        model = models.UserInfo
        fields = ['username', 'email', 'password', 'confirm_password', 'mobile_phone', 'code']


def register(request):
    form = RegisterModelForm()
    return render(request, 'blogAPP/register.html', {'form': form})


def index(request):
    conn = get_redis_connection("default")

    conn.set('nickname', "zjl", ex=10)
    value = conn.get('nickname')
    print(value)
    return HttpResponse("OK")